package nio.base;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class FileChannelLockTest2 {

    public static void main(String[] args) throws IOException, InterruptedException {

        final RandomAccessFile file = new RandomAccessFile("read.txt", "rw");
        final RandomAccessFile file2 = new RandomAccessFile("read.txt", "rw");
        final FileChannel channel = file.getChannel();
        final FileChannel channel2 = file2.getChannel();
        Runnable d = () -> {
            try {
                System.out.println("channel:" + Thread.currentThread().getName());
                final FileLock lock = lock(channel);
                System.out.println("channel get");
                Thread.sleep(1000);
                lock.release();
                System.out.println("channel release");
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        };
        Runnable d2 = () -> {
            try {
                System.out.println("channel2:" + Thread.currentThread().getName());
                final FileLock lock = lock(channel);
                System.out.println("channel2 get");
                Thread.sleep(1000);
                lock.release();
                System.out.println("channel2 release");
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        };
        new Thread(d).start();
        new Thread(d2).start();
    }

    public static FileLock lock(FileChannel channel) {

        FileLock lock = null;
        do {
            try {
                lock = channel.lock();
                System.out.println(Thread.currentThread().getName() + ":" + lock);
                Thread.sleep(100);
            } catch (Exception e) {
            }
        } while (lock == null);
        return lock;
    }
}
